<template>
  <div class="material-management-page">
    <!-- 页头 -->
    <div class="page-header">
      <h1>材料管理</h1>
      <p>维护原料信息、库存预警、入库操作</p>
    </div>

    <!-- 库存预警 -->
    <el-alert
        v-if="hasWarningItems"
        title="警告：有材料库存低于阈值，请及时补充！"
        type="warning"
        show-icon
        closable
        class="warning-alert"
    />

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left-tools">
        <el-button type="primary" icon="Plus" @click="openFormModal('add')">
          新增材料
        </el-button>
        <el-button icon="Refresh" :loading="tableLoading" @click="loadMaterials" />
      </div>

      <div class="filter-tools">
        <!-- 类型 -->
        <el-select
            v-model="typeFilter"
            placeholder="材料类型"
            clearable
            style="width: 160px"
            @change="handleFilterChange"
        >
          <el-option label="全部类型" value="" />
          <el-option label="基础原料" value="基础原料" />
          <el-option label="小料" value="小料" />
          <el-option label="包装材料" value="包装材料" />
        </el-select>

        <!-- 库存状态 -->
        <el-select
            v-model="stockFilter"
            placeholder="库存状态"
            clearable
            style="width: 160px"
            @change="handleFilterChange"
        >
          <el-option label="全部状态" value="" />
          <el-option label="库存正常" value="normal" />
          <el-option label="低于阈值" value="warning" />
        </el-select>

        <!-- 搜索 -->
        <el-input
            v-model="searchQuery"
            placeholder="搜索材料名称 / 供应商"
            prefix-icon="Search"
            clearable
            style="width: 260px"
            @input="handleSearch"
        />
      </div>
    </div>

    <!-- 表格 -->
    <el-table
        :data="tableData"
        v-loading="tableLoading"
        border
        stripe
        highlight-current-row
        empty-text="暂无数据"
        class="materials-table"
    >
      <el-table-column type="index" label="序号" width="70" align="center" />
      <el-table-column
          prop="ingredientName"
          align="center"
          label="材料名称"
          min-width="140"
          show-overflow-tooltip
      />
      <el-table-column prop="ingredientType" label="类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="typeTagType(row.ingredientType)">
            {{ row.ingredientType }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="采购总量" width="110" align="center" >
        <template #default="{ row }">
          {{ row.quantity }} {{ row.unit }}
        </template>
      </el-table-column>

      <el-table-column label="当前库存" width="130" align="center" >
        <template #default="{ row }">
          <span :class="row.stock < row.threshold ? 'text-danger' : ''">
            {{ row.stock }} {{ row.unit }}
          </span>
          <el-tag v-if="row.stock < row.threshold" type="danger" size="small" class="ml-2">
            预警
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="库存阈值" width="130" align="center" >
        <template #default="{ row }">
          {{ row.threshold }} {{ row.unit }}
        </template>
      </el-table-column>

      <el-table-column prop="supplier" label="供应商" min-width="150" align="center"  show-overflow-tooltip />

      <el-table-column label="操作" width="280" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary"  icon="Edit" @click="openFormModal('edit', row)" style="text-align: center;" >
            编辑
          </el-button>
          <el-button size="small" type="success" icon="Plus" @click="openStockModal(row)" style="text-align: center;" >
            入库
          </el-button>
          <el-button size="small" type="danger" icon="Delete" @click="confirmDelete(row)" style="text-align: center;" >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10]"
    @current-change="handlePageChange"
    />
    <!-- 新增/编辑弹窗 -->
    <el-dialog
        :title="formTitle"
        v-model="formVisible"
        width="600px"
        top="5vh"
        :close-on-click-modal="false"
    >
      <el-form
          ref="materialForm"
          :model="formData"
          :rules="formRules"
          label-width="110px"
      >
        <el-form-item label="材料名称" prop="ingredientName">
          <el-input v-model="formData.ingredientName" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="材料类型" prop="ingredientType">
          <el-select v-model="formData.ingredientType" placeholder="请选择">
            <el-option label="基础原料" value="基础原料" />
            <el-option label="小料" value="小料" />
            <el-option label="包装材料" value="包装材料" />
          </el-select>
        </el-form-item>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="采购总量" prop="quantity">
              <el-input-number
                  v-model="formData.quantity"
                  :min="0"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="formData.unit" placeholder="单位">
                <el-option
                    v-for="u in unitOptions"
                    :key="u"
                    :label="u"
                    :value="u"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="当前库存" prop="stock">
              <el-input-number
                  v-model="formData.stock"
                  :min="0"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存阈值" prop="threshold">
              <el-input-number
                  v-model="formData.threshold"
                  :min="0"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="formData.supplier" placeholder="请输入供应商" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 入库弹窗 -->
    <el-dialog
        title="入库"
        v-model="stockDialogVisible"
        width="500px"
        top="10vh"
        :close-on-click-modal="false"
    >
      <el-descriptions :column="2" size="small" border>
        <el-descriptions-item label="材料名称">
          {{ currentMaterial?.ingredientName }}
        </el-descriptions-item>
        <el-descriptions-item label="当前库存">
          {{ currentMaterial?.stock }} {{ currentMaterial?.unit }}
        </el-descriptions-item>
        <el-descriptions-item label="库存阈值">
          {{ currentMaterial?.threshold }} {{ currentMaterial?.unit }}
        </el-descriptions-item>
      </el-descriptions>

      <el-form
          ref="stockForm"
          :model="stockFormData"
          :rules="stockRules"
          label-width="100px"
          style="margin-top: 16px"
      >
        <el-row :gutter="12">
          <el-col :span="16">
            <el-form-item label="入库数量" prop="amount">
              <el-input-number
                  v-model="stockFormData.amount"
                  :min="0.1"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-select v-model="stockUnit" placeholder="单位">
              <el-option
                  v-for="u in unitOptions"
                  :key="u"
                  :label="u"
                  :value="u"
              />
            </el-select>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
              v-model="stockFormData.remark"
              type="textarea"
              :rows="2"
              placeholder="选填"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="stockLoading" @click="submitStockChange">
          确认入库
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认 -->
    <el-dialog
        title="确认删除"
        v-model="deleteDialogVisible"
        width="400px"
        :close-on-click-modal="false"
    >
      <p>
        确定删除
        <span class="text-danger font-bold">{{ currentMaterial?.ingredientName }}</span>
        吗？
      </p>
      <p class="text-warning mt-8">删除后数据将无法恢复，请谨慎操作！</p>

      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="deleteLoading" @click="performDelete">
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/axios/http'   // 按你实际路径

/* ------------------ 基础变量 ------------------ */
const tableData = ref([])
const total = ref(0)
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

const typeFilter = ref('')
const stockFilter = ref('')
const searchQuery = ref('')

const formVisible = ref(false)
const formTitle = ref('')
const formType = ref('add')
const formLoading = ref(false)

const stockDialogVisible = ref(false)
const stockLoading = ref(false)
const stockUnit = ref('')
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)

const currentMaterial = ref(null)

const unitOptions = reactive(['个', '千克', '克', '升', '毫升', '片', '根', '块', '包', '盒'])

const formData = reactive({
  id: null,
  ingredientName: '',
  ingredientType: '',
  quantity: 0,
  unit: '',
  stock: 0,
  threshold: 0,
  supplier: ''
})

const stockFormData = reactive({
  amount: 0.1,
  remark: ''
})

const formRules = {
  ingredientName: [{ required: true, message: '请输入材料名称', trigger: 'blur' }],
  ingredientType: [{ required: true, message: '请选择材料类型', trigger: 'change' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }]
}

const stockRules = {
  amount: [{ required: true, message: '请输入入库数量', trigger: 'blur' }]
}

/* ------------------ 计算属性 ------------------ */
const hasWarningItems = computed(() => tableData.value.some(m => m.stock < m.threshold))

/* ------------------ 方法 ------------------ */
const typeTagType = type => {
  switch (type) {
    case '基础原料': return 'primary'
    case '小料': return 'success'
    case '包装材料': return 'info'
    default: return 'default'
  }
}

/* 统一加载列表（含搜索/筛选/分页） */
// const loadMaterials = async () => {
//   tableLoading.value = true
//   try {
//     const dto = {
//       pageNum: currentPage.value,
//       pageSize: pageSize.value,
//       ingredientName: searchQuery.value || null,
//       ingredientType: typeFilter.value || null,
//       stockStatus: stockFilter.value || null
//     }
//     const res = await http.post('/glsb/ingredients/get_all_redients', dto)
//     if (res.data.result === 'success') {
//       tableData.value = res.data.data.records
//       total.value = res.data.data.total
//     } else {
//       ElMessage.error(res.data.message || '加载失败')
//     }
//   } catch (e) {
//     ElMessage.error('网络异常')
//   } finally {
//     tableLoading.value = false
//   }
// }
const loadMaterials = async () => {
  tableLoading.value = true
  try {
    const res = await http.post('/glsb/ingredients/search', {
      pageNum: currentPage.value,
      keyword: searchQuery.value,          // 名称/供应商模糊
      ingredientType: typeFilter.value,    // 类型
      stockStatus: stockFilter.value       // normal / warning
    })
    if (res.data.result === 'success') {
      tableData.value = res.data.data.records
      total.value = res.data.data.total
    } else {
      ElMessage.error(res.data.message || '加载失败')
    }
  } finally {
    tableLoading.value = false
  }
}

/* 新增/编辑弹窗 */
const openFormModal = (type, row = null) => {
  formType.value = type
  formTitle.value = type === 'add' ? '新增材料' : '编辑材料'
  formVisible.value = true
  Object.assign(formData, {
    id: row?.id || null,
    ingredientName: row?.ingredientName || '',
    ingredientType: row?.ingredientType || '',
    quantity: row?.quantity ?? 0,
    unit: row?.unit || '',
    stock: row?.stock ?? 0,
    threshold: row?.threshold ?? 0,
    supplier: row?.supplier || ''
  })
}

/* 保存材料 */
const submitForm = async () => {
  formLoading.value = true
  try {
    const res = await http.post('/glsb/ingredients', formData)
    if (res.data.result === 'success') {
      ElMessage.success(formType.value === 'add' ? '添加成功' : '更新成功')
      formVisible.value = false
      loadMaterials()
    } else {
      ElMessage.error(res.data.message || '操作失败')
    }
  } finally {
    formLoading.value = false
  }
}

/* 入库弹窗 */
const openStockModal = row => {
  currentMaterial.value = row
  stockFormData.amount = 0.1
  stockFormData.remark = ''
  stockUnit.value = row.unit
  stockDialogVisible.value = true
}

/* 确认入库 */
const submitStockChange = async () => {
  stockLoading.value = true
  try {
    const res = await http.post('/glsb/ingredients/stock/in', {
      id: currentMaterial.value.id,
      amount: stockFormData.amount
    })
    if (res.data.result === 'success') {
      ElMessage.success('入库成功')
      stockDialogVisible.value = false
      loadMaterials()
    } else {
      ElMessage.error(res.data.message || '入库失败')
    }
  } finally {
    stockLoading.value = false
  }
}

/* 删除 */
const confirmDelete = row => {
  currentMaterial.value = row
  deleteDialogVisible.value = true
}
const performDelete = async () => {
  deleteLoading.value = true
  try {
    const res = await http.delete(`/glsb/ingredients/${currentMaterial.value.id}`)
    if (res.data.result === 'success') {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      loadMaterials()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  } finally {
    deleteLoading.value = false
  }
}

/* 筛选 & 搜索 */
const handleFilterChange = () => {
  currentPage.value = 1
  loadMaterials()
}
let searchTimer = null
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    loadMaterials()
  }, 400)
}
const handleSizeChange = val => {
  pageSize.value = val
  currentPage.value = 1
  loadMaterials()
}
const handlePageChange = val => {
  currentPage.value = val
  loadMaterials()
}

/* ------------------ 初始化 ------------------ */
onMounted(() => loadMaterials())
</script>

<style scoped>
/* 与原来保持一致，略 */
.material-management-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}
.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1d2129;
}
.warning-alert {
  margin-bottom: 16px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}
.left-tools {
  display: flex;
  gap: 8px;
}
.filter-tools {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
.text-danger {
  color: #f56c6c;
}
.text-warning {
  color: #e6a23c;
}
.font-bold {
  font-weight: 600;
}
.mt-8 {
  margin-top: 8px;
}
.ml-2 {
  margin-left: 8px;
}
</style>